import socket
import sys
import struct
import time
import tcp
import threading
import _thread
import pymysql


# 本程序是应变传感器采集,可以通过发送ALL指令进行全部传感器的采集


def crc16(string):
    # data = bytes.fromhex(string)
    data = string
    crc = 0xFFFF
    for pos in data:
        crc ^= pos

        for i in range(8):
            if ((crc & 1) != 0):
                crc >>= 1
                crc ^= 0xA001
            else:
                crc >>= 1
    return hex(((crc & 0xff) << 8) + (crc >> 8))


# 连接数据
def MySQLConnect():
    connection = pymysql.connect(
        host='localhost',  # IP，MySQL数据库服务器IP地址
        port=3306,  # 端口，默认3306，可以不输入
        user='root',  # 数据库用户名
        password='zhoushuai123',  # 数据库登录密码
        database='mysql',  # 要连接的数据库
        charset='utf8'  # 字符集，注意不是'utf-8'
    )
    return connection


# 插入数据到数据库
def AddData(num, yb, wd, time):
    # 连接数据库
    conn = MySQLConnect()

    # 使用cursor()方法创建一个游标对象cursor
    cursor = conn.cursor()
    # 插入数据库
    sql = "INSERT INTO test(id ,mic, strain_temp, time) VALUES (%s,%s,%s,%s); "
    cursor.execute(sql, [num, yb, wd, time])
    # 提交事务
    conn.commit()
    # 关闭游标
    cursor.close()
    # 关闭数据库连接
    conn.close()


# 获取一次数据
def getStain(cmd, num, time):
    # print(cmd)
    # print(num)
    # print("cmd_16: ", cmd)
    cmd = bytes.fromhex(cmd)
    # print("cmd_byte: ", cmd)
    crc = crc16(cmd)
    crc = bytes.fromhex(crc[2:])
    cmd = cmd + crc
    # 发送对应的指令
    tcp.send(cmd)
    try:
        data = tcp.recv(8192)
    except socket.timeout:
        print("超时")
        sys.exit(1)
    crc = data[-2:]
    crc1 = crc16(data[:-2])
    crc1 = crc1[2:]
    if len(crc1) == 3:
        crc1 = '0' + crc1
    crc1 = bytes.fromhex(crc1)
    if crc != crc1:
        print("CRC16校验失败！")
        sys.exit(2)
    print(len(data))
    yb, wd = struct.unpack('>ii', data[4:12])
    yb = yb / 100.0
    wd = wd / 100.0
    print("应变：", yb, "温度：", wd)
    print(time)
    yb = str(yb)
    wd = str(wd)
    print("id: ", num, "mic: ", yb, "strain_temp: ", wd, "time: ", time)
    AddData(num, yb, wd, time)


def setCircleData(cmd, num):
    count = 0
    flag = 0
    last = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    last1 = time.time()
    while True:
        now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        now1 = time.time()
        # print(now)
        if (flag == 0):
            count = count + 1
            flag = 1
            getStain(cmd, num, last)
            last = now
            last1 = now1
        if now1 - last1 > 5:
            if count >= 5:
                str = input("请选择是否继续采集（y表示继续，n表示退出）：")
                if str == 'y':
                    count = 0
                    continue
                else:
                    break
            count = count + 1
            getStain(cmd, num, now)
            last = now
            last1 = now1


# 同时采集全部应变传感器
def setCircleAll(cmd):
    flag = 0
    count = 0
    last = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    last1 = time.time()
    while True:
        now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        now1 = time.time()
        # count=0
        # print(now)
        if (flag == 0):
            flag = 1
            count = count + 1
            for cmd1 in cmd:
                id = '00' + cmd1[0:2]
                # print(id)
                # print(cmd1)
                getStain(cmd1, id, last)
            last = now
            last1 = now1
        if now1 - last1 > 5:
            if count >= 5:
                str = input("请选择是否继续采集（y表示继续，n表示退出）：")
                if str == 'y':
                    count = 0
                    continue
                else:
                    break
            count = count + 1
            for cmd1 in cmd:
                id = '00' + cmd1[0:2]
                getStain(cmd1, id, now)
            last = now
            last1 = now1


if __name__ == '__main__':
    tcp = socket.socket(socket.AF_INET,
                        socket.SOCK_STREAM,
                        socket.IPPROTO_TCP)
    tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    tcp.settimeout(5)
    try:
        tcp.connect(('demo-monitor.igong.com', 8002))
        print("TCP连接成功")
    except:
        print("连接TCP失败")
        sys.exit(1)
    flag = 0
    while True:
        print("具体指令给格式为000+传感器编号（1，2，3，4，5）")
        num = input("请输入采集传感器的编号（All表示采集全部传感器,0表示退出采集）：")
        if num == '0001':
            cmd = '010300010002'
            setCircleData(cmd, num)

        elif num == '0002':
            cmd = '020300010002'
            setCircleData(cmd, num)

        elif num == '0003':
            cmd = '030300010002'
            setCircleData(cmd, num)
        elif num == '0004':
            cmd = '040300010002'
            setCircleData(cmd, num)
        elif num == '0005':
            cmd = '050300010002'
            setCircleData(cmd, num)
        elif num == 'All':
            cmd = {'010300010002', '020300010002', '030300010002', '040300010002', '050300010002'}
            setCircleAll(cmd)
        elif num == '0':
            break
        else:
            print("输入信息不合法，请重新输入")

